﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace iLangl.Model
{
	public class SyncedDataRequestContext : BaseContext
	{
		SyncedOneWayData request = null;
		public override void SetContext(object context)
		{
			base.SetContext(context);

			if (context is SyncedOneWayData)
			{
				request = context as SyncedOneWayData;
			}
		}

		public override object GetContext()
		{
			if (request == null)
				return string.Empty;

			startDocument();
			writer.WriteStartElement("SyncedData");
			
			if ((request.Companies != null) && (request.Companies.Length > 0))
			{
				writer.WriteStartElement("Companies");
				
				CompanyRequestContext companyRequestContext = new CompanyRequestContext();
				foreach (Company company in request.Companies)
				{
					companyRequestContext.SetContext(company);
					companyRequestContext.Write(writer);
				}

				writer.WriteEndElement();
			}

			if ((request.Projects != null) && (request.Projects.Length > 0))
			{
				writer.WriteStartElement("Projects");

				ProjectRequestContext projectRequestContext = new ProjectRequestContext();
				foreach (Project project in request.Projects)
				{
					projectRequestContext.SetContext(project);
					projectRequestContext.Writer(writer);
				}

				writer.WriteEndElement();
			}

			if ((request.Alerts != null) && (request.Alerts.Length > 0))
			{
				writer.WriteStartElement("Alerts");

				foreach (ISerializedAlert alert in request.Alerts)
				{
					writer.WriteStartElement("Alert");
					writer.WriteAttributeString("id", alert.Id);
					writer.WriteAttributeString("source", alert.Source);
					writer.WriteAttributeString("created", alert.Created.ToString(DefaultSettingsManager.DateTimeFormat));
					writer.WriteAttributeString("severity", alert.Severity.ToString());
					writer.WriteStartElement("Content");
					writer.WriteCData(alert.Content);
					writer.WriteEndElement();

					if (alert.PackageIds != null)
					{
						writer.WriteStartElement("Packages");
						writer.WriteCData(String.Join(",", alert.PackageIds));
						writer.WriteEndElement();
					}

					writer.WriteEndElement();
				}

				writer.WriteEndElement();
			}

			writer.WriteEndElement();
			return endDocument();
		}
	}
}
